<?php

namespace App\Admin\Actions;

use App\Constant\Enum;
use App\Models\GroupMember;
use App\Models\User;
use App\Services\Group\GroupService;
use Dcat\Admin\Contracts\LazyRenderable;
use Dcat\Admin\Traits\LazyWidget;
use Dcat\Admin\Widgets\Form;
use Illuminate\Support\Facades\DB;


class SetParentForm extends Form implements LazyRenderable
{
    use LazyWidget;

    public function handle(array $input)
    {
        $userId = $input['user_id'] ?? 0;
        $parentId  = $input['parent_id'] ?? 0;

        /** @var User $user */
        $user = User::query()->findOrFail($userId);

        /** 2025-6-18 增加基本信息昵称 头像独立修改逻辑 */
        $nickname  = $input['nickname'] ?? "";
        $avatar  = $input['avatar'] ?? "";
        $baseInfoAttributes = [
            'nickname' => $nickname,
            'avatar' => $avatar
        ];
        $user->update($baseInfoAttributes);

        if ($user->parent_id != 0 && $user->is_admin_related == 0) {
            return response()->json([
                'code' => 400,
                'message' => '自然绑定关系无法修改'
            ]);
        }

        if (GroupMember::query()->where([
            'user_id' => $userId,
        ])->exists()) {
            return response()->json([
                'code' => 400,
                'message' => '该用户为团长邀请，无法修改绑定关系！'
            ]);
        }

        $attributes = [
            'parent_id' => 0,
            'is_admin_related' => 1,
        ];

        DB::beginTransaction();
        try {
            if (!empty($parentId)) {
                /** @var User $parent */
                $parent = User::query()->findOrFail($parentId);
                if (!empty($parent->parent_id)) {
                    if ($parent->parent_id == $userId) {
                        return response()->json([
                            'code' => 400,
                            'message' => '禁止循环绑定关系'
                        ]);
                    }
                }

                $attributes['parent_id'] = $parent->id;
                if ($parent) {
                    $group = GroupService::findLatestGroup($parent);
                    if ($group) {
                        GroupService::addMember($group, $user);
                    }
                }
            }

            $user->update($attributes);
            DB::commit();
            return response()->json([
                'code' => 200,
                'message' => '操作成功！'
            ]);
        } catch (\Exception $e) {
            DB::rollBack();
            return response()->json([
                'code' => 500,
                'message' => $e->getMessage()
            ]);
        }
    }

    public function form()
    {
        // update by 2025年7月3日
        $this->hidden('user_id')->value($this->payload['key']);
        /** @var User $user */
        $user = User::query()->find($this->payload['key']);

        $this->image('avatar', '头像')
            ->autoUpload()->url(url('filebase/upload'))->value($user->getAttribute('avatar')); // 回显已上传的头像路径;

        $this->text('nickname', '昵称')
            ->value($user->getAttribute('nickname'));

        $this->text('username', '用户')->readOnly()
            ->value(sprintf('%s(%s)', $user->getAttribute('uuid'), $user->getAttribute('nickname')));

        $query = User::query()
            ->where('id', '!=', $user->getAttribute('id'))
            ->select('uuid', 'id', 'nickname');
        $list = $query->get();


        $options = [];
        foreach ($list as $item) {
            $options[$item->id] = sprintf("%s(%s)", $item->uuid, $item->nickname);
        }

        $this->select('parent_id', '上级')->options($options);
    }

    /**
     * 设置表单保存成功后执行的JS
     *
     * @return string|void
     */
    protected function savedScript()
    {
        return <<<JS
        if (data.code != 200) {
            Dcat.error(data.message);
            return false;
        }

        Dcat.success(data.message);
        Dcat.reload();

        return false;
JS;
    }

    /**
     * 设置表单保存失败后执行的JS
     *
     * @return string|void
     */
    protected function errorScript()
    {
        return <<<JS
        var errorData = JSON.parse(response.responseText);
        if (errorData) {
            if (errorData.message) {
                Dcat.error(errorData.message);
            } else {
                Dcat.error("封禁原因必填");
            }
        } else {
            console.log('提交出错', response.responseText);
        }
        // 终止后续逻辑执行（默认逻辑）
        return false;
JS;
    }
}
